package cn.lyjuan.archetypes.bms.web.controller.base;

import cn.lyjuan.archetypes.bms.web.config.AppUserDetail;
import cn.lyjuan.archetypes.bms.web.util.SpringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.List;

public class SecurityController extends BaseController
{
    public AppUserDetail user()
    {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (!auth.isAuthenticated())
            return null;

        AppUserDetail user = (AppUserDetail) auth.getPrincipal();

        return user;
    }

    /**
     * 获取当前登陆用户名
     *
     * @return
     */
    public String getUserName()
    {
        return getRealUser().getUsername();
    }

    public Integer getUserId()
    {
        return getRealUser().getRealUser().getId();
    }

    public AppUserDetail getRealUser()
    {
        UserDetails user = SpringUtils.getUserPrincipal();
        return (AppUserDetail) user;
    }

    /**
     * 获取当前登陆用户权限
     *
     * @return
     */
    public List<SimpleGrantedAuthority> getAuthorities()
    {
        return (List<SimpleGrantedAuthority>) SpringUtils.getUserPrincipal().getAuthorities();
    }
}
